/*
 * @Author: sunzhijun 
 * @Date: 2019-03-24 20:39:23 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-04-15 16:10:30
 */
/*
 * 传入this.props以便调用方法
 * @agFlag: 是否进入协议签订
 * @appCode: 本节点调用其他节点code
 * pkOrg: 组织节点
 */

import React, {Component} from 'react';
import {promptBox, base, toast} from 'nc-lightapp-front';
import {hrAjax as ajax, saveValidate} from 'src/hrpub/common/utils/utils';
import {chectFormAction} from '../../../../../public/functions/checkFormAction';
import handdleCheckedData from '../../../../../public/functions/checkDataPermissionAction';
import deepCopy from '../../../../../../hrpub/common/utils/deep-copy';
const { NCButton, NCSelect, NCCheckbox } = base;

const moduleId = "sign6011";
const domainName = "hrcm";

class FormCard extends Component{
    constructor(props){
        super(props);
        this.state = {
            json: {},
            dataCard_add : '', //formCard Id 初始为空
            pk_org: props.pkOrg
        }
        this.formrelationArr = ['traincontAgreeInfo_add','traincontTrainInfo_add','traincontBusinessInfo_add'];
        this.setFormCardId = this.setFormCardId.bind(this);
    }

    componentWillMount() {
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({json, inlt})//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: moduleId, domainName: domainName, callback})
    }

    componentDidMount() {
        
    }

    //设置formrelation
    setFormrelation(){
        let { agreementType }  = this.state;
        let template = {
            formrelation: {
                traincontCard_add: this.formrelationArr
            }    
        }
        if( agreementType == 'traincont'){
            this.props.meta.addMeta(template);
        }else{
            let getMeta = this.props.meta.getMeta().formrelation;
            let getFormrelation =  getMeta && getMeta.formrelation;
            if(!!getFormrelation) {
                delete getFormrelation.traincontCard_add;
                template.formrelation = getFormrelation;
                this.props.meta.addMeta(template);
            }
        }
    }

    //获取formCard模板及数据
    getFormCardData(selectData,agreementType){ 
        let pk_psnjob = [];
        selectData && selectData.map((v,i)=>{
            pk_psnjob.push(v.data.values.pk_psnjob.value);
        });
        let storage = window.localStorage.getItem('pageQueryParam');
        let sign_pk_psnjob = storage && storage.sign && storage.sign.pk_psndoc_subs;
        let psnJobs = !!pk_psnjob.length ? pk_psnjob : sign_pk_psnjob;
        let areaCode = 'dataCard';
        let areaCodeCard = '';
        let { agFlag, pkOrg } = this.props;
        let appCode = this.props.appCode;
        let code = {
            appCode: appCode ? appCode : ''
        }
        if(!!agreementType){
            areaCode = agreementType +'Card';
            this.setState({
                agreementType: agreementType,
                dataCard_add: ''
            })
        }
        areaCodeCard = areaCode + '_add';
        if(!!psnJobs){
            ajax ({
                url: '/nccloud/hrcm/common/DataInitAction.do',
                data: {
                    pk_psnjobs: psnJobs,
                    areaCode: areaCode,
                    appCode: appCode,
                    pk_org: pkOrg,
                    agreementType: agreementType || ''   //选中的协议类型
                },
                success: res => {
                    if(res.success){
                        let data = res.data;
                        let resultItems = data.resultData[areaCodeCard];
                        let template = {
                            [areaCodeCard]: data.template[areaCodeCard],
                            traincontAgreeInfo_add : data.template.traincontAgreeInfo_add,
                            traincontTrainInfo_add: data.template.traincontTrainInfo_add,
                            traincontBusinessInfo_add: data.template.traincontBusinessInfo_add,
                            dataCard_value: resultItems   //缓存本地待编辑数据备用
                        }
                        this.setState({
                            formrelation: data.formrelation[areaCodeCard]
                        })
                        // 自定义的协议注册
                        let registed = this.props.registed;
                        let temp = deepCopy(template);
                        for (let key in temp) {
                            if(temp.hasOwnProperty(key) && temp[key].moduletype){
                                if(!registed.includes(temp[key].code)) {
                                    temp[key].moduletype === 'form' && this.props.use.form(temp[key].code);
                                    temp[key].moduletype === 'table' && this.props.use.editTable(temp[key].code);
                                }
                        　　}
                        }
                        
                        this.props.meta.addMeta(template);
                        this.setFormrelation();
                        this.setFormCardId(areaCodeCard,data.rollBackFlag,resultItems);
                    }
                },
                error: err => {
                    toast({color:"danger",content: err.message});
                    this.props.childPrevHandle && this.props.childPrevHandle();
                }
            })
        }
    }

    //点击是否立即生效事件
    isTakeEffectEvent(agreementType,listData,savedCtrtpks,step){
        !!savedCtrtpks && handdleCheckedData(savedCtrtpks, 'effect', 'agreement', ()=>{
            this.doneAgreementData(agreementType,listData,savedCtrtpks,step);
        });
    }

    //协议点击完成保存
    doneAgreementData(agreementType,listData,data,step){
        let { formrelation, dataCard_add } = this.state;
        let selectFormData = this.props.form.getAllFormValue(dataCard_add).rows;
        let pk_psnjobArr = listData;
        let bodys_code = null;
        let billType = 'form';
        // listData && listData.map((v,i)=>{
        //     pk_psnjobArr.push(v.data.values.pk_psnjob.value);
        // })
        let formData = {
            model: {
                rows: selectFormData
            }
        }
        if(!this.props.form.isCheckNow(dataCard_add)){
            return false;
        }
        if(!!formrelation && formrelation.length > 0){
            bodys_code = formrelation;
            billType = 'extcard';
        }
        saveValidate(this.props, dataCard_add, dataCard_add, bodys_code, billType).then(()=>{
            ajax({
                url: '/nccloud/hrcm/agreement/SignAddSaveAction.do',
                data: {
                    step: step || '0',
                    agreementType: agreementType,
                    pkPsnjobs: pk_psnjobArr,
                    formData: formData,
                    savedCtrtpks: data || []
                },
                success: res => {
                    if(res.success){
                        let data = res.data;
                        let step = data.step;
                        let savedCtrtpks = data.savedCtrtpks;
                        if(step == '1'){
                            let fn = {
                                sureFn: () => this.isTakeEffectEvent(agreementType,listData,savedCtrtpks,step),
                                cancelFn :()=> this.props.closeModal && this.props.closeModal(savedCtrtpks)
                            }
                            this.promptBoxModal(data.msg, fn);
                        }else{
                            this.props.closeModal();
                        }
                    }
                }
            })
        })
    }
    //设置页面FormCar Id
    setFormCardId(id,flag,data){
        let { agreementType } = this.state;
        this.props.setRollBackFlag(flag, agreementType);
        this.setState({
            dataCard_add: id,
            rollBackFlag: flag
        },()=>{
            this.props.form.setAllFormValue({[id]: data});
            this.props.form.setFormStatus(id,'edit');
            if(data && data.rows[0].values.ifprop.value === true){
                this.props.form.setFormItemsValue(id,{'ifprop':{display: null, value: "Y", scale: "-1"}})
            }else{
                this.props.form.setFormItemsValue(id,{'ifprop':{display: null, value: "N", scale: "-1"}})
            }
        })
    }

    //卡片日期设置
    handleEditFormDate(props,moduleId,key,value){
        let { dataCard_add } = this.state;
        chectFormAction(key, moduleId, props, [dataCard_add]);
    }

    //编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data){
        let { agreementType, pk_org} = this.state;
        if(key === 'pk_conttext'){
            let obj = {
                "pk_org": pk_org,
                "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder",
                "agreementType": agreementType
            }
            this.setQueryCondition(moduleId, key, obj);
        }else if(key  === 'pk_post'){
            let pk_dept = data['pk_psnjob.pk_dept.pk_dept'] && data['pk_psnjob.pk_dept.pk_dept'].value;
            let obj = {
                "pk_dept": pk_dept
            }
            this.setQueryCondition(moduleId, key, obj);
        }
        return true;
    }

    // 编辑前事件操作增加queryCondition条件
    setQueryCondition(moduleId, key, param){
        let meta = this.props.meta.getMeta();
        if(!!meta[moduleId].items.find(item => item.attrcode === key)){
            meta[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                return param
            };
        }else{
            meta['traincontAgreeInfo_add'].items.find(item => item.attrcode === key).queryCondition = function () {
                return param
            };
        }
        this.props.meta.setMeta(meta);
    }

    //获取formCard Id
    getFormCardId(){
        let formCardId = this.state.dataCard_add;
        return formCardId;
    }

    //确认弹窗
    promptBoxModal(context,fn = {},args){ //context 内容；fn 执行的方法；args 传递的参数
        let { sureFn, cancelFn } = fn;
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: this.state.json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: this.state.json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: this.state.json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn:true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick:  ()=> { sureFn && sureFn(args) } ,   // 确定按钮点击调用函数,非必输
            cancelBtnClick:  ()=>{ cancelFn && cancelFn(args) },  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop:false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }

    render(){
        let { form, agFlag, appCode } = this.props;
        let { createForm } = form;
        let { dataCard_add } = this.state;
        return (
            dataCard_add ? 
            createForm(dataCard_add, {
                useFixedHeader: true,
                onAfterEvent: this.handleEditFormDate.bind(this),
                onBeforeEvent: this.handleEditBefore.bind(this),
                expandArr: ['traincontAgreeInfo_add','traincontTrainInfo_add','traincontBusinessInfo_add'], // 设置关联表单某个区域展开
            }) : ''
        )
    }
}

export default FormCard;